package jam.UserInterface.UI;
import jam.network.NetworkController;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import jam.model.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import jam.network.message.*;
import java.io.IOException;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.util.*;
import jam.model.ClientModel;
public class mainWindow extends JFrame implements ActionListener, KeyListener, MouseListener{
    
    // the main frame for the main window
    private JFrame mainFrame = new JFrame();
    
    //the main, left and right panes to hold all of the components
    private JPanel mainPane = new JPanel();
    private JPanel leftPane = new JPanel();
    private JPanel rightPane = new JPanel();
    private JPanel bottomPane = new JPanel();
    
    //a picture panel for the users avatar and contacts avatar
    private JPanel picPanel = new JPanel();
    private JPanel avatarPanel = new JPanel();
    
    //a label to hold the image
    private JLabel pic;
    
    
    //the tabbed panes for the userchats and contactlist
    private JTabbedPane userChats = new JTabbedPane();
    private JTabbedPane contactList = new JTabbedPane();
    
    //the file menu and menu options
    private JMenuBar fileMenu = new JMenuBar();
    private JMenu file = new JMenu();
    private JMenu options = new JMenu();
    private JMenuItem logOff = new JMenuItem();
    
    //the user menu
    private JMenuBar userMenu = new JMenuBar();
    private JMenu userOptions = new JMenu();
    
    //the user menu items
    private JMenuItem logOut = new JMenuItem();
    private JMenuItem uOptions = new JMenuItem();
    private JMenu changeStatus = new JMenu();
    private JMenuItem green = new JMenuItem();
    private JMenuItem red = new JMenuItem();
    private JMenuItem grey = new JMenuItem();
    private JMenuItem yellow = new JMenuItem();
    private JMenuItem changeColour = new JMenuItem();
    private JMenuItem uploadAvatar = new JMenuItem();
    
    //the buttons for the user interface
    private JButton style = new JButton();
    private JButton smiley = new JButton();
    private JButton addUser = new JButton();

    //stuff to switch between the users that you are chatting too
    private JScrollPane tabPane;
    private JLabel spacing;
    private JScrollPane messagePane;
    private int index = -1;
    private HashMap<Integer,String[]> userChatLog = new HashMap<Integer,String[]>();	
    private String testUsers[] = {"david@isawesome.com","smcquistin@gmail.com","Aga","i91scott@gmail.com","knifacat@gmail.com","Ted Johnson","Bob","Superman","Batman","Robocop"};
    
    //the EditorPanes/textAreas for the chatlog the messagebox and the searchbox
    private JEditorPane chatLog = new JEditorPane();
    private JEditorPane messageBox = new JEditorPane();
    private JTextArea searchBox = new JTextArea();
    
    //JPanel for the contacts in the contact list
    JPanel contactPanel = new JPanel(new GridBagLayout());
    
    //the users displayname
    String displayName;
    
    // sample channels for the channel list
    private String[] sampleChannels = {"Sample Channel 1", "Sample Channel 2", "Sample Channel 3" ,"..."};
    
    //sample active conversations for the conversation list
    private String[] sampleConvo = {"Sample Conversation 1", "Sample Conversation 2", "Sample Conversation 3", "..."};
    
    //the colour of the window
    
    private Color colour = Color.orange;
    
    //status label
    private JLabel status;

    //The users avatar picture
    private Image avatarPic;
    
    //a list to hold the active contacts
    private ArrayList<User> activeContacts = new ArrayList<User>();
    private ArrayList<String> activeConvos = new ArrayList<String>();

    //the current user that the logged in user is talking too
    private String currentUser;
    private String currentChannel;
    private JList contacts;

    //testing some shit out
    private JLabel test;

    private ClientModel cModel;
	
    //GridBagConstraints
    GridBagConstraints c = new GridBagConstraints();
    
    public mainWindow(String displayName, ClientModel cl){
	this.displayName = displayName;
	cModel = cl;
	
	//optional look and feel
	UIManager.LookAndFeelInfo[] lfi= UIManager.getInstalledLookAndFeels();
	
	try
	    {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	    }
	catch (Exception e)
	    {
		System.out.println("Can't set chosen look-and-feel!");
	    }
	
	mainFrame.setDefaultLookAndFeelDecorated(true);
	
	//initialising the mainFrame with its size and settings
	
	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	mainFrame.setTitle("JAM");
	mainFrame.setBounds(((int)(screenSize.getWidth()-600))/2,((int)(screenSize.getHeight()-600))/2,600,600);
	mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);			
	mainFrame.setBackground(Color.LIGHT_GRAY);
	
	//change the icon code
	String currentDirectory = System.getProperty("user.dir");
	try {
	    Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
	    mainFrame.setIconImage(image);
	}catch (Exception e){System.out.println(e.getMessage());}
	
	mainPane.setLayout(new GridBagLayout());
	mainPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
	
	// set up the file menu
	
	file.setText("File");
	logOff.setText("Log Off");
	logOff.addActionListener(this);
	
	file.add(logOff);
	
	fileMenu.add(file);
	
	mainFrame.setJMenuBar(fileMenu);
	
	//initialising the left pane
	leftPane.setLayout(new GridBagLayout());
	leftPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	leftPane.setPreferredSize(new Dimension(315,600));
	
	c.fill = GridBagConstraints.BOTH;

	//adding the leftpane to the main pane
	c.weightx = 0.5;
	c.weighty = 0.5;
	c.gridx = 0;
	c.gridy = 0;
	mainPane.add(leftPane,c);
	
	//initialising the rightPane 
	rightPane.setLayout(new GridBagLayout());
	rightPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	rightPane.setPreferredSize(new Dimension(285,600));
	
	// setting up the user menu
	userOptions.setText(displayName);
	
	//logOut option
	logOut.setText("Log Out");
	logOut.addActionListener(this);
	
	//change status option
	changeStatus.setText("changeStatus");
	changeStatus.addActionListener(this);
	
	//add the status options
	green.setText("Available");
	green.addActionListener(this);
	
	red.setText("Busy");
	red.addActionListener(this);
	
	grey.setText("Appear Offline");
	grey.addActionListener(this);
	
	yellow.setText("Away");
	yellow.addActionListener(this);
	
	changeStatus.add(grey); changeStatus.add(green); changeStatus.add(yellow); changeStatus.add(red);
	
	//change colour option
	changeColour.setText("ChangeColour");
	changeColour.addActionListener(this);
	
	//user options option
	uOptions.setText("User Options");
	uOptions.addActionListener(this);
	
	//upload avatar option
	uploadAvatar.setText("Upload Avatar");
	uploadAvatar.addActionListener(this);
	
	userOptions.add(changeStatus);
	userOptions.add(changeColour);
	userOptions.add(logOut);
	userOptions.add(uOptions);
	userOptions.add(uploadAvatar);
	
	userMenu.add(userOptions);
	
	c.gridx = 0;
	c.gridy = 0;
	
	try {
	    Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
	    image = image.getScaledInstance(40, 40, 0);
	    
	    pic = new JLabel(new ImageIcon(image));
	    pic.setFocusable(true);
	    pic.setPreferredSize(new Dimension(20,20));
	    picPanel.setLayout(new GridBagLayout());
	    picPanel.add(pic,c);
	}catch (Exception e){System.out.println("The file could not be read!!!!");}			
	
	c.gridx = 1;
	c.fill = GridBagConstraints.CENTER;
	picPanel.add(userMenu,c);
	c.fill = GridBagConstraints.BOTH;
	c.gridx = 0;
	rightPane.add(picPanel,c);
	//status label
	try{
	    avatarPic = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/StatusIcons/user-online-2.png"));	
	    status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
	    status.setHorizontalTextPosition(JLabel.LEADING);
	    status.setPreferredSize(new Dimension(280,20));
	    c.gridx = 0;
	    c.gridy = 1;
	    rightPane.add(status,c);
	}catch (Exception e){ System.out.println("The file wasn't there!!!");}
	
	// a list to hold the contacts

	ArrayList<JPanel> testArray = new ArrayList<JPanel>();
	for (int i = 0; i < 10; i++){
	    test = new JLabel();
	    try {
		JPanel testPanel = new JPanel(new GridBagLayout());
		Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
		test.setIcon(new ImageIcon(image));
		test.setText(testUsers[i]);
		c.gridy = i;
		testPanel.add(test,c);
		testArray.add(testPanel);
	    }catch (Exception e){System.out.println("The file could not be read!!!!");}	
	}
	
	Object[] panels = testArray.toArray();
	
	contacts = new JList(panels);
	contacts.setCellRenderer(new ImageListCellRenderer());
	contacts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	contacts.setLayoutOrientation(JList.VERTICAL);
	contacts.addMouseListener(this);
	JScrollPane conList = new JScrollPane(contacts);
	conList.setPreferredSize(new Dimension(280,500));
	conList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	
	// a list to hold the channels
	JList channels = new JList(sampleChannels);
	JScrollPane chaList = new JScrollPane(channels);
	chaList.setPreferredSize(new Dimension(280,500));
	chaList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	
	//a list to hold the active conversations
	JList conversations = new JList(sampleConvo);
	JScrollPane convoList = new JScrollPane(conversations);
	convoList.setPreferredSize(new Dimension(280,500));
	convoList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	
	//initialise the contact list
	contactList.setPreferredSize(new Dimension(280,400));
	contactList.setMinimumSize(new Dimension(280,400));
	
	contactList.addTab("Contact List", conList);
	contactList.addTab("Channel List", chaList);
	contactList.addTab("Active Conversations", convoList);
	
	c.gridx = 0;
	c.gridy = 2;	
	rightPane.add(contactList,c);
	
	addUser.setText("Add User");
	addUser.addActionListener(this);
	addUser.setPreferredSize(new Dimension(280,20));
	
	c.gridx = 0;
	c.gridy = 3;
	c.fill = GridBagConstraints.CENTER;
	rightPane.add(addUser,c);
	
	c.fill = GridBagConstraints.BOTH;
	
	searchBox.setPreferredSize(new Dimension(280,20));
	searchBox.setFocusable(true);
	searchBox.addKeyListener(this);
	searchBox.addMouseListener(this);
	searchBox.setLineWrap(true);
	searchBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	searchBox.setText("Search");
	searchBox.setForeground(Color.LIGHT_GRAY);
	
	c.gridx = 0;
	c.gridy = 4;
	rightPane.add(searchBox,c);
	
	//adding the rightPane to the mainPane
	c.gridx = 2;
	c.gridy = 0;
	mainPane.add(rightPane,c);
	
	//adding the mainPane to the mainFrame and showing the mainFrame
	mainFrame.add(mainPane);
	mainFrame.setVisible(true);
    }
    
    public mainWindow(Color colour, final String name, JEditorPane chatLog, Image avatar){
	this.displayName = name;
	this.colour = colour;
	this.chatLog = chatLog;
	this.avatarPic = avatar;
	
	//optional look and feel
	UIManager.LookAndFeelInfo[] lfi= UIManager.getInstalledLookAndFeels();
	
	try
	    {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	    }
	catch (Exception e)
	    {
		System.out.println("Can't set chosen look-and-feel!");
	    }
	
	mainFrame.setDefaultLookAndFeelDecorated(true);
	
	//initialising the mainFrame with its size and settings
	
	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	mainFrame.setTitle("JAM");
	mainFrame.setBounds(((int)(screenSize.getWidth()-600))/2,((int)(screenSize.getHeight()-600))/2,600,600);
	mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);			
	mainFrame.setBackground(colour);
	
	//change the icon code
	String currentDirectory = System.getProperty("user.dir");
	try {
	    Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
	    mainFrame.setIconImage(image);
	}catch (Exception e){System.out.println("The file could not be read!!!!");}
	
	//initialising the main pane
	mainPane.setLayout(new GridBagLayout());
	mainPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
	mainPane.setOpaque(true);
	mainPane.setBackground(colour);
	
	// set up the file menu
	
	file.setText("File");
	logOff.setText("Log Off");
	logOff.addActionListener(this);
	
	file.add(logOff);
	
	fileMenu.add(file);
	fileMenu.setOpaque(true);
	fileMenu.setBackground(colour);
	
	mainFrame.setJMenuBar(fileMenu);
	
	//initialising the left pane
	leftPane.setLayout(new GridBagLayout());
	leftPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	leftPane.setSize(315,600);
	leftPane.setOpaque(true);
	leftPane.setBackground(colour);
	
	c.fill = GridBagConstraints.BOTH;

	//adding the leftpane to the main pane
	c.weightx = 0.5;
	c.weighty = 0.5;
	c.gridx = 0;
	c.gridy = 0;
	mainPane.add(leftPane,c);
	
	//initialising the rightPane 
	rightPane.setLayout(new GridBagLayout());
	rightPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	rightPane.setPreferredSize(new Dimension(285,600));
	rightPane.setOpaque(true);
	rightPane.setBackground(colour);	
	
	// setting up the user menu
	userOptions.setText(displayName);
	
	//logOut option
	logOut.setText("Log Out");
	logOut.addActionListener(this);
	
	//change status option
	changeStatus.setText("changeStatus");
	changeStatus.addActionListener(this);
	
	
	//add the status options
	green.setText("Available");
	green.addActionListener(this);
	
	red.setText("Busy");
	red.addActionListener(this);
	
	grey.setText("Appear Offline");
	grey.addActionListener(this);
	
	yellow.setText("Away");
	yellow.addActionListener(this);
	
	changeStatus.add(grey); changeStatus.add(green); changeStatus.add(yellow); changeStatus.add(red);
	
	//change colour option
	changeColour.setText("ChangeColour");
	changeColour.addActionListener(this);
	
	
	//user options option
	uOptions.setText("User Options");
	uOptions.addActionListener(this);
	
	//upload avatar option
	uploadAvatar.setText("Upload Avatar");
	uploadAvatar.addActionListener(this);
	
	userOptions.add(changeStatus);
	userOptions.add(changeColour);
	userOptions.add(logOut);
	userOptions.add(uOptions);
	userOptions.add(uploadAvatar);
	
	userMenu.add(userOptions);
	
	try {
	    Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
	    image = image.getScaledInstance(40, 40, 0);
	    
	    pic = new JLabel(new ImageIcon(image));			
	    pic.setPreferredSize(new Dimension(20,20));
	    picPanel.setLayout(new GridBagLayout());
	    picPanel.add(pic,c);
	    picPanel.setOpaque(true);
	    picPanel.setBackground(colour);
	}catch (Exception e){System.out.println("The file could not be read!!!!");}		
	
	c.gridx = 0;
	c.gridy = 0;
	c.gridx = 1;
	c.fill = GridBagConstraints.CENTER;
	picPanel.add(userMenu,c);
	c.fill = GridBagConstraints.BOTH;
	c.gridx = 0;
	rightPane.add(picPanel,c);
	
	//status label
	try{
	    status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
	    status.setHorizontalTextPosition(JLabel.LEADING);
	    status.setPreferredSize(new Dimension(280,20));
	    c.gridx = 0;
	    c.gridy = 1;
	    rightPane.add(status,c);
	}catch (Exception e){ System.out.println("The file wasn't there!!!");}
	
	ArrayList<JPanel> testArray = new ArrayList<JPanel>();

	for (int i = 0; i < 10; i++){
	    test = new JLabel();
	    try {
		JPanel testPanel = new JPanel(new GridBagLayout());
		Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
		test.setIcon(new ImageIcon(image));
		test.setText(testUsers[i]);
		c.gridy = i;
		testPanel.add(test,c);
		testArray.add(testPanel);
	    }catch (Exception e){System.out.println("The file could not be read!!!!");}	
	}
	
	Object[] panels = testArray.toArray();
	
	JList contacts = new JList(panels);
	contacts.setCellRenderer(new ImageListCellRenderer());
	contacts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	contacts.setLayoutOrientation(JList.VERTICAL);
	contacts.addMouseListener(this);
	JScrollPane conList = new JScrollPane(contacts);
	conList.addMouseListener(this);
	conList.setPreferredSize(new Dimension(280,500));
	conList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	
	// a list to hold the channels
	JList channels = new JList(sampleChannels);
	channels.setOpaque(true);
	channels.setBackground(colour);
	JScrollPane chaList = new JScrollPane(channels);
	chaList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	chaList.setPreferredSize(new Dimension(280,500));
	chaList.setOpaque(true);
	chaList.setBackground(colour);
	
	//a list to hold the active conversations
	JList conversations = new JList(sampleConvo);
	conversations.setOpaque(true);
	conversations.setBackground(colour);
	JScrollPane convoList = new JScrollPane(conversations);
	convoList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	convoList.setPreferredSize(new Dimension(280,500));
	convoList.setOpaque(true);
	convoList.setBackground(colour);
	
	//initialise the contact list
	contactList.setPreferredSize(new Dimension(280,400));
	contactList.setMinimumSize(new Dimension(280,400));
	contactList.setOpaque(true);
	contactList.setBackground(colour);
	
	contactList.addTab("Contact List", conList);
	contactList.addTab("Channel List", chaList);
	contactList.addTab("Active Conversations", convoList);
	
	c.gridx = 0;
	c.gridy = 2;	
	rightPane.add(contactList,c);
	
	addUser.setText("Add User");
	addUser.addActionListener(this);
	addUser.setPreferredSize(new Dimension(280,20));
	addUser.setOpaque(true);
	addUser.setBackground(colour);
	
	c.gridx = 0;
	c.gridy = 3;
	c.fill = GridBagConstraints.CENTER;
	rightPane.add(addUser,c);
	
	c.fill = GridBagConstraints.BOTH;
	
	searchBox.setPreferredSize(new Dimension(280,20));
	searchBox.setFocusable(true);
	searchBox.addKeyListener(this);
	searchBox.addMouseListener(this);
	searchBox.setLineWrap(true);
	searchBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	searchBox.setText("Search");
	searchBox.setForeground(Color.LIGHT_GRAY);
	
	c.gridx = 0;
	c.gridy = 4;
	rightPane.add(searchBox,c);
	
	//adding the rightPane to the mainPane
	c.gridx = 2;
	c.gridy = 0;
	mainPane.add(rightPane,c);
	
	//adding the mainPane to the mainFrame and showing the mainFrame
	mainFrame.add(mainPane);
	mainFrame.setVisible(true);
	
    }
    
    //the main method for invoke our UI
    /* public static void main(String args[]){
	SwingUtilities.invokeLater(new Runnable(){
		public void run(){
		    new mainWindow("test"); // creates the user interface
		}
	    });
    }*/
    
    public void updateActiveContacts(){
	//in here we will update the active contact list display
    }
    
    
    public void updateContacts(ArrayList<User> contacts){
	//check to see if the active contacts list needs to be updated
	boolean check = false;
	for (int i = 0; i < contacts.size(); i++){
	    User contact = contacts.get(i);
	    for (int j = 0;  j < activeContacts.size(); j++){
		User activeContact = activeContacts.get(j);
		if (contact.getDName().equals(activeContact.getDName()) && !contact.getAvatar().equals(activeContact.getAvatar()) || !contact.getStatus().equals(activeContact.getStatus())){
		    activeContact.setAvatar(contact.getAvatar());
		    activeContact.setStatus(contact.getStatus());
		    check = true;
		}
	    }
	}
	
	if (check == true){
	    updateActiveContacts();
	}
	
	for (int i = 0; i < contacts.size(); i++){
	    JLabel contact = new JLabel(contacts.get(i).getDName());
	    try{
		Image image = ImageIO.read(new File(contacts.get(i).getAvatar()));
		contact.setIcon(new ImageIcon(image));
	    }catch (Exception e){System.out.println("The file could not be read!!!!");}	
	    Color statusColour = Color.getColor(contacts.get(i).getStatus());
	    contact.setForeground(statusColour);
	    contactPanel.add(contact);
	    
	}
	contactList.remove(contactPanel);
	contactList.add(contactPanel);
	
	}
    
    
    //action, key, component and event listeners for our different components
    

    @Override
	public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub
	if (e.getSource() == addUser){
	    SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
			new addUserWindow(); // creates the user interface
		    }
		});
	}
	
	if (e.getSource() == style){
	    fontPickerWindow fp = new fontPickerWindow(messageBox);
	    fp.dispose();
	}
	
	
	if (e.getSource() == logOut || e.getSource() == logOff){
	    mainFrame.dispose();
	    ClientActionLogout l = new  ClientActionLogout();
	    NetworkController.send(l.toString());
	}
	
	if (e.getSource() == uOptions){
	    SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
			new userOptions(); // creates the user interface
		    }
		});
	}
	
	if (e.getSource() == changeColour){
	    SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
			new colourChooserWindow(mainFrame,displayName,chatLog,avatarPic); // creates the user interface
		    }
		});
	}
	
	if (e.getSource() == smiley){
	    SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
			new ButtonsGrid(messageBox); // creates the user interface
		    }
		});
	}
	
	if (e.getSource() == uploadAvatar){
	    SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
			uploadAvatarWindow avatar = new uploadAvatarWindow(picPanel, pic); // creates the user interface
			avatar.dispose();
		    }
		});
	}
	
	if (e.getSource() == green){
	    rightPane.remove(status);
	    try{
		String currentDirectory = System.getProperty("user.dir");
		avatarPic = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/StatusIcons/user-online-2.png"));	
		status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
		status.setHorizontalTextPosition(JLabel.LEADING);
		c.gridx = 0;
		c.gridy = 1;
		rightPane.add(status,c);
		rightPane.revalidate();
	    }catch (Exception a){ System.out.println("The file wasn't there!!!");}
	}
	else if (e.getSource() == red){
	    rightPane.remove(status);
	    try{
		String currentDirectory = System.getProperty("user.dir");
		avatarPic = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/StatusIcons/user-busy-2.png"));
		status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
		status.setHorizontalTextPosition(JLabel.LEADING);
		c.gridx = 0;
		c.gridy = 1;
		rightPane.add(status,c);
		rightPane.revalidate();
	    }catch (Exception a){ System.out.println("The file wasn't there!!!");}
	}
	else if (e.getSource() == grey){
	    rightPane.remove(status);
	    try{
		String currentDirectory = System.getProperty("user.dir");
		avatarPic = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/StatusIcons/user-offline-2.png"));
		status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
		status.setHorizontalTextPosition(JLabel.LEADING);
		c.gridx = 0;
		c.gridy = 1;
		rightPane.add(status,c);
		rightPane.revalidate();
	    }catch (Exception a){ System.out.println("The file wasn't there!!!");}
	}
	else if (e.getSource() == yellow){
	    rightPane.remove(status);
	    try{
		String currentDirectory = System.getProperty("user.dir");
		avatarPic = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/StatusIcons/user-extended-away.png"));
		status = new JLabel("Status: ", new ImageIcon(avatarPic), JLabel.LEFT);
		status.setHorizontalTextPosition(JLabel.LEADING);
		c.gridx = 0;
		c.gridy = 1;
		rightPane.add(status,c);
		rightPane.revalidate();
	    }catch (Exception a){ System.out.println("The file wasn't there!!!");}
	}
    }
    
    @Override
	public void keyPressed(KeyEvent e) {
	// TODO Auto-generated method stub
    }
    
    @Override
	public void keyReleased(KeyEvent e) {
	// TODO Auto-generated method stub
	if(e.getSource() == messageBox && e.getKeyCode() == KeyEvent.VK_ENTER && !messageBox.getText().trim().isEmpty()){
	    //converts the smiles from the text type to images
	    AutoreplaceSmiles convert = new AutoreplaceSmiles(messageBox);
	    Color msgCol = messageBox.getForeground();
	    Font msgFont = messageBox.getFont();
	    String msgText = messageBox.getText();
	    HTMLDocument chatLogDoc = (HTMLDocument)chatLog.getDocument();
	    Element body = chatLogDoc.getDefaultRootElement();
	    body = body.getElement(0);
	    body = body.getElement(0);
	    String fontWeight = "normal";
	    if(msgFont.isBold()) fontWeight = "bold";
	    String fontStyle = "normal";
	    if(msgFont.isItalic()) fontStyle = "italic";
	  
	    String styledMsg = "<font style='font-style: "+fontStyle+"; font-weight: "+fontWeight+"; font-size: "+msgFont.getSize()+"pt;"+
		" font-family: \""+msgFont.getFamily()+"\"; color: rgb("+msgCol.getRed()+","+msgCol.getGreen()+","+msgCol.getBlue()+");'>"+ messageBox.getText().replace("\n","")+"</font><br>";


	    ArrayList<String> tempArrayList = cModel.getChannels();
	    

	    for (int i = 0; i < tempArrayList.size(); i++){
		if (tempArrayList.get(i).contains(currentUser)){
		    currentChannel = tempArrayList.get(i);
		}	    
	    }
	    ClientActionMessage message = new ClientActionMessage(currentChannel, styledMsg);
	    NetworkController.send(message.toString());

	    styledMsg = "<font style='font-style: "+fontStyle+"; font-weight: "+fontWeight+"; font-size: "+msgFont.getSize()+"pt;"+
				" font-family: \""+msgFont.getFamily()+"\"; color: rgb("+msgCol.getRed()+","+msgCol.getGreen()+","+msgCol.getBlue()+");'>"+
			displayName + " says:<br>" +  messageBox.getText()+"</font><br>";
	    try{
		chatLogDoc.insertBeforeEnd(body,styledMsg);
		}catch(BadLocationException BL){}
		catch(IOException io){}
	    messageBox.setFont(msgFont);
	    messageBox.setText("");
	    String tempChatLog = chatLog.getText();
	    removeComponents();	
	    changeUser(currentUser, tempChatLog);	    
	}
	
    }

    public void incomingMessage(String user, String text){
	System.out.println(user);
	if (user.equals(currentUser)){
	    AutoreplaceSmiles convert = new AutoreplaceSmiles(messageBox);
	    Color msgCol = messageBox.getForeground();
	    Font msgFont = messageBox.getFont();
	    String msgText = messageBox.getText();
	    HTMLDocument chatLogDoc = (HTMLDocument)chatLog.getDocument();
	    Element body = chatLogDoc.getDefaultRootElement();
	    body = body.getElement(0);
	    body = body.getElement(0);
	    String fontWeight = "normal";
	    if(msgFont.isBold()) fontWeight = "bold";
	    String fontStyle = "normal";
	    if(msgFont.isItalic()) fontStyle = "italic";
	    text = user + " says:<br><br>" + text;
	    try{
		//System.out.println("This is happening!");
		chatLogDoc.insertBeforeEnd(body,text);
	    }catch(BadLocationException BL){}
	    catch(IOException io){}
	    //System.out.println(chatLog.getText());
	    messageBox.setFont(msgFont);
	    String tempMsgBox = messageBox.getText();
	    String tempChatLog = chatLog.getText();
	    removeComponents();
	    changeUser(user,tempChatLog);
	    messageBox.setText(tempMsgBox);
	}
	else {
	    int index = 0;
	    for (int i = 0; i < testUsers.length; i++){
		if (testUsers[i].equals(user)){ index = i;}
	    }
	    contacts.setSelectedIndex(index);
	    contacts.setSelectionBackground(Color.yellow);
	    if (userChatLog.containsKey(index)){
		String tempArray[] = userChatLog.get(index);
		String tempString = tempArray[1];
		int position = tempString.indexOf("</font>");
		String firstString = tempString.substring(0,position);
		String lastString = tempString.substring(position,tempString.length());
		tempString = firstString + user + "says:<br><br>" +  text + lastString;
		tempArray[1] = tempString;
		userChatLog.put(index,tempArray);
	    }
	    else {
		String tempArray[] = new String[2];
		tempArray[0] = user;
		tempArray[1] = user + " says:<br><br>" + text;
		userChatLog.put(index,tempArray);
	    }
	}
	    
    }
    
    @Override
	public void keyTyped(KeyEvent e) {
	// TODO Auto-generated method stub
	
    }
    
    @Override
	public void mouseClicked(MouseEvent e) {
	// TODO Auto-generated method stub	
	if (e.getClickCount() == 2){
	    JList list = (JList) e.getSource();
	    int index = list.locationToIndex(e.getPoint());
	    if (this.index == -1){
		this.index = index;
		String name;
		String tempArray[];
		if (userChatLog.containsKey(index)){
		    tempArray = userChatLog.get(index);
		    removeComponents();
		    changeUser(tempArray[0],tempArray[1]);
		    currentUser = tempArray[0];
		    currentChannel = tempArray[0]+displayName;
		    activeConvos.add(currentChannel);
		}
		else {
		    name = testUsers[index];
		    String chatLogText = " ";
		    tempArray = new String[2];
		    tempArray[0] = name; 
		    tempArray[1] = chatLogText;
		    userChatLog.put(index,tempArray);
		    removeComponents();
		    changeUser(name,chatLogText);	
		    System.out.println(name);
		    ClientActionJoinChannel join = new ClientActionJoinChannel((name + displayName).toLowerCase());
		    NetworkController.send(join.toString());
		    ClientActionInvite invite = new ClientActionInvite(name, name + displayName);
		    currentChannel = name+displayName.toLowerCase();
		    activeConvos.add(currentChannel);
		    NetworkController.send(invite.toString());
		    currentUser = name;
		}
	    }
	    else {
		String name = testUsers[this.index];
		String tempArray[] = userChatLog.get(this.index);
		tempArray[1] = chatLog.getText();
		userChatLog.put(this.index,tempArray);
		this.index = index;
		if (userChatLog.containsKey(index)){
		    tempArray = userChatLog.get(index);
		    removeComponents();
		    changeUser(tempArray[0],tempArray[1]);
		    currentUser = tempArray[0];
		    currentChannel = tempArray[0]+displayName;
		    activeConvos.add(currentChannel);
		}
		else {
		    name = testUsers[index];
		    String chatLogText = " ";
		    tempArray = new String[2];
		    tempArray[0] = name; 
		    tempArray[1] = chatLogText;
		    userChatLog.put(index,tempArray);
		    removeComponents();
		    changeUser(name,chatLogText);
		    System.out.println(name);
		    ClientActionJoinChannel join = new ClientActionJoinChannel((name + displayName).toLowerCase());
		    NetworkController.send(join.toString());
		    ClientActionInvite invite = new ClientActionInvite(name, name + displayName);
		    currentChannel = name+displayName.toLowerCase();
		    activeConvos.add(currentChannel);
		    NetworkController.send(invite.toString());
		    currentUser = name;
		}    
	    }  
	}
    }

    private void removeComponents(){
	userChats.removeAll();
	userChats.revalidate();
	userChats.repaint();
	leftPane.removeAll();
	leftPane.revalidate();
	leftPane.repaint();
	bottomPane.removeAll();
	bottomPane.repaint();
	style = null;
	smiley = null;
	mainPane.remove(leftPane);
	mainPane.revalidate();
	mainPane.repaint();
    }
	
    private void changeUser(String name, String chatText){
	
	chatLog.setEditable(false);
	chatLog.setContentType("text/html");
	chatLog.setPreferredSize(new Dimension(310,320));
	chatLog.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	chatLog.setText(chatText);
	
	//initialising the internal pane to go into the userchat tabbed pane    
	
	tabPane = new JScrollPane(chatLog);
	tabPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
	
	tabPane.setPreferredSize(new Dimension(310,320));
	tabPane.setMinimumSize(new Dimension(310,320));
	//adding some spacing to the tabPane
	spacing = new JLabel();
	spacing.setText(" ");
	spacing.setPreferredSize(new Dimension(310,20));
	
	//initialising the messageBox
	messageBox.setContentType("text/plain");
	messageBox.setPreferredSize(new Dimension(310,140));
	messageBox.addKeyListener(this);
	messageBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	messageBox.setCaretPosition(0);
	
	//adding the items to the leftpane
	userChats.addTab(name,tabPane);
	
	c.weightx = 0.5;
	c.weighty = 0.5;
	c.gridx = 0;
	c.gridy = 0;
	leftPane.add(userChats,c);
	
	c.gridx = 0;
	c.gridy = 1;
	leftPane.add(spacing,c);
	
	messagePane = new JScrollPane(messageBox);
	messagePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
	messagePane.setPreferredSize(new Dimension(310,150));
	messagePane.setMinimumSize(new Dimension(310,150));
	
	c.gridx = 0;
	c.gridy = 2;	
	leftPane.add(messagePane,c);
	
	//initialising the bottom pane with its buttons
	bottomPane.setLayout(new GridBagLayout());
	bottomPane.setPreferredSize(new Dimension(310,50));
	style = new JButton();
	style.setText("Style");
	style.addActionListener(this);
	smiley = new JButton();
	smiley.setText(":)");
	smiley.addActionListener(this);
	
	//adding the bottom pane to the left pane
	c.gridx = 0;
	c.gridy = 0;
	bottomPane.add(style);
	c.gridx = 1;
	c.gridy = 0;
	bottomPane.add(smiley);	
	c.gridx = 0;
	c.gridy = 3;
	leftPane.add(bottomPane,c);
	leftPane.revalidate();
	leftPane.repaint();
	c.gridx = 0;
	c.gridy = 0;
	mainPane.add(leftPane, c);
	mainPane.revalidate();
	mainPane.repaint();
    }
    
    @Override
	public void mouseEntered(MouseEvent e) {
	// TODO Auto-generated method stub
    }
    
    @Override
	public void mouseExited(MouseEvent e) {
	// TODO Auto-generated method stub
	
    }
    
    @Override
	public void mousePressed(MouseEvent e) {
	// TODO Auto-generated method stub
	if (e.getSource() == searchBox && searchBox.getText().equals("Search")){
	    searchBox.setText("");
	    searchBox.setForeground(Color.BLACK);
	}
    }
    
    @Override
	public void mouseReleased(MouseEvent e) {
	// TODO Auto-generated method stub
	
    }
    
}
